import { NextRequest, NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// 数值对应的段位名称
const TIER_NAMES: Record<number, string> = {
  1: 'HT1',
  2: 'LT1',
  3: 'HT2',
  4: 'LT2',
  5: 'HT3',
  6: 'LT3',
  7: 'HT4',
  8: 'LT4',
  9: 'HT5',
  10: 'LT5'
};

// 段位名称对应的数值
const TIER_VALUES: Record<string, number | null> = {
  '无等级': null,
  'HT1': 1,
  'LT1': 2,
  'HT2': 3,
  'LT2': 4,
  'HT3': 5,
  'LT3': 6,
  'HT4': 7,
  'LT4': 8,
  'HT5': 9,
  'LT5': 10
};

// 获取段位名称，处理null值
function getTierName(tier: number | null): string {
  if (tier === null) return '无等级';
  return TIER_NAMES[tier] || 'LT5';
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const playerId = parseInt(params.id);
    if (isNaN(playerId)) {
      return NextResponse.json(
        { error: '无效的玩家ID' },
        { status: 400 }
      );
    }

    const body = await request.json();
    const { 
      swordTier,   // 剑
      crystalTier, // 水晶
      buhcTier,    // UHC
      potionTier,  // 药水
      npotTier,    // 无药水
      smpTier      // SMP
    } = body;

    // 检查玩家是否存在
    const existingPlayer = await prisma.player.findUnique({
      where: {
        id: playerId,
      },
    });

    if (!existingPlayer) {
      return NextResponse.json(
        { error: '玩家不存在' },
        { status: 404 }
      );
    }

    // 更新段位信息
    const updatedPlayer = await prisma.player.update({
      where: {
        id: playerId,
      },
      data: {
        swordTier,
        crystalTier,
        buhcTier,
        potionTier,
        npotTier,
        smpTier
      },
    });

    // 解析地区信息
    let player_region = updatedPlayer.region;
    let player_region_id = null;
    let player_region_color = null;
    let player_is_blacklisted = false;
    
    // 检查是否为黑名单
    if (player_region && player_region.includes('[blacklisted]')) {
      player_is_blacklisted = true;
      player_region = player_region.replace('[blacklisted]', '');
    }
    
    // 解析地区ID和颜色
    if (player_region && player_region.includes('|')) {
      const parts = player_region.split('|');
      player_region = parts[0];
      player_region_id = parts[1];
      player_region_color = parts[2];
    }

    // 转换段位为名称
    const formattedPlayer = {
      ...updatedPlayer,
      id: updatedPlayer.id.toString(),
      region: player_region,
      region_id: player_region_id,
      region_color: player_region_color,
      is_blacklisted: player_is_blacklisted,
      // 转换为段位名称
      tier_names: {
        sword: getTierName(updatedPlayer.swordTier),
        crystal: getTierName(updatedPlayer.crystalTier),
        buhc: getTierName(updatedPlayer.buhcTier),
        potion: getTierName(updatedPlayer.potionTier),
        npot: getTierName(updatedPlayer.npotTier),
        smp: getTierName(updatedPlayer.smpTier),
      },
      // 保留原始数值
      tiers: {
        sword: updatedPlayer.swordTier,
        crystal: updatedPlayer.crystalTier,
        buhc: updatedPlayer.buhcTier,
        potion: updatedPlayer.potionTier,
        npot: updatedPlayer.npotTier,
        smp: updatedPlayer.smpTier,
      }
    };

    return NextResponse.json(formattedPlayer);
  } catch (error) {
    console.error('更新玩家段位失败:', error);
    return NextResponse.json(
      { error: '更新玩家段位失败' },
      { status: 500 }
    );
  }
} 